package com.stottlerhenke.simbionic.engine.parser;
import com.stottlerhenke.simbionic.engine.core.*;
import com.stottlerhenke.simbionic.api.*;
import com.stottlerhenke.simbionic.common.parser.ETernaryOp;
import com.stottlerhenke.simbionic.common.parser.SB_ExpressionNode;


public class SB_ExpTernaryOp extends SB_Expression {
  protected SB_Expression _arg1;
  protected SB_Expression _arg2;
  protected SB_Expression _arg3;
  protected ETernaryOp _op;

  public SB_ExpTernaryOp(SB_ExpressionNode arg1, SB_ExpressionNode arg2, SB_ExpressionNode arg3, ETernaryOp op) {
    super();
    _arg1 = (SB_Expression)arg1;
    _arg2 = (SB_Expression)arg2;
    _arg3 = (SB_Expression)arg3;
    _op = op;
  }
  public EExpressionType GetType() { return EExpressionType.kTernary; }
  
  /**
   * Replaces all instances of SB_Method in the expression tree that
   * match the name of newMethod.
   * @param newMethod the method with which to replace existing methods
   */
  public void replaceFunction(SB_Function newMethod)
  {
      _arg1.replaceFunction(newMethod);
      _arg2.replaceFunction(newMethod);
      _arg3.replaceFunction(newMethod);
  }
  
  public SB_Variable Evaluate(SB_Entity entity, SB_ExecutionFrame contextFrame) throws SB_Exception {
    SB_Variable arg1 = _arg1.Evaluate(entity, contextFrame);

    boolean head = (arg1 == null) ? false : arg1.bool();
    
    return head ? _arg2.Evaluate(entity,contextFrame) : _arg3.Evaluate(entity,contextFrame);
  }

  public String PrintTree() throws SB_Exception
  {
    String out = new String("(");
    out += _arg1.PrintTree();
    out += " ? ";
    out += _arg2.PrintTree();
    out += " : ";
    out += _arg3.PrintTree();

    return out + ")";
  }
  
}
